package com.biz.service.weixin;

import com.biz.model.Pmodel.weixin.AccessToken;
import com.biz.model.Pmodel.weixin.JsApiTicket;
import com.biz.utils.ConfigUtil;
import com.biz.utils.UuidUtil;
import com.framework.dao.mdao.DaoSupport;
import com.framework.util.Tools;
import com.framework.util.weixin.EnumMethod;
import com.framework.util.weixin.HttpRequestUtil;
import com.framework.util.weixin.WechatAccessToken;
import com.framework.util.weixin.WechatJsApiTicket;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lzq on 2017/2/9.
 */
@Service("wxUtilService")
public class WXUtilService {

	@Resource(name = "daoSupport")
	private DaoSupport dao;


	/**
	 * 获取AccessToken
	 *
	 * @return
	 */
	public  String getAccessToken()
	{
		String newAccessToken = "";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = (Map<String, Object>)dao.findForObject("WxUtilDao.getWxTicketById", null);
		} catch (Exception e) {

		}
		if(map == null )
		{
			newAccessToken = reloadAccessToken("", "1").getToken();
		}else if(map !=null && map.get("ACCESS_TOKEN") == null){
			newAccessToken = reloadAccessToken((String) map.get("id"), "0").getToken();
		}else if(map !=null && map.get("ACCESS_TOKEN") != null){
			String accessTokenStr = (String) map.get("ACCESS_TOKEN");
			if (Tools.isEmpty(accessTokenStr))
			{
				System.out
						.println("################################################");
				System.out.println("载入JsApiTicket已超时，重新载入");
				System.out
						.println("################################################");
				newAccessToken = reloadAccessToken((String) map.get("id"), "0").getToken();
			}
			else
			{
				String[] accessTokenArg = accessTokenStr.split(",");
				long nowTime = new Date().getTime();
				long putTime=0,diffTime=0;
				if(accessTokenArg[1]!=null){
					putTime = Long.parseLong(accessTokenArg[1]);
				}
				if(accessTokenArg[2]!=null){
					diffTime = Long.parseLong(accessTokenArg[2]);
				}
				if (Math.abs(nowTime - putTime) >= diffTime)
				{
					System.out
							.println("################################################");
					System.out.println("载入token已超时，重新载入");
					System.out
							.println("################################################");
					newAccessToken = reloadAccessToken((String) map.get("id"),"0").getToken();
				}
				if(!select_accessToken(accessTokenArg[0]))//是否有效
				{
					System.out.println("载入JsApiTicket已超时，重新载入");
					newAccessToken = reloadAccessToken((String) map.get("id"),"0").getToken();
				}
				else
				{
					newAccessToken = accessTokenArg[0];
				}
			}
		}

		return newAccessToken;
	}

	/**
	 * 重新装载AccessToken
	 *
	 * @return
	 */
	public AccessToken reloadAccessToken(String id, String type)
	{
		String appId = ConfigUtil.get("appId");
		String secret = ConfigUtil.get("appSecret");
		AccessToken accessToken = WechatAccessToken.getAccessToken(appId,
				secret);
		Map<String, String> map = new HashMap<String, String>();
		if("1".equals(type)){
			map.put("id", UuidUtil.get32UUID());
		}else{
			map.put("id", id);
		}
		map.put("ACCESS_TOKEN", accessToken.getToken() + ","
				+ new Date().getTime() + "," + (accessToken.getExpiresIn() * 1000));
		try {
			if("1".equals(type))//添加
			{
				dao.save("WxUtilDao.saveAccessToken",map);
			}else{
				dao.update("WxUtilDao.updateAccessToken",map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return accessToken;
	}

	/**
	 * 获取JsApiTicket
	 *
	 * @return
	 */
	public  String getJsApiTicket()
	{
		String newJsApiTicket = "";
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			map = (Map<String, Object>)dao.findForObject("WxUtilDao.getWxTicketById", null);
		} catch (Exception e) {

		}
		if(map == null )
		{
			newJsApiTicket = reloadJsApiTicket("", "1").getTicket();
		}else if(map !=null && map.get("JSAPI_TICKET") == null){
			newJsApiTicket = reloadJsApiTicket((String) map.get("id"), "0").getTicket();
		}else if(map !=null && map.get("JSAPI_TICKET") != null) {
			String jsApiTicketStr = (String) map.get("JSAPI_TICKET");
			if (Tools.isEmpty(jsApiTicketStr)) {
				System.out
						.println("################################################");
				System.out.println("载入JsApiTicket已超时，重新载入");
				System.out
						.println("################################################");
				newJsApiTicket = reloadJsApiTicket((String) map.get("id"), "0").getTicket();
			} else {
				String[] jsApiTicketArg = jsApiTicketStr.split(",");
				long nowTime = new Date().getTime();
				long putTime = Long.parseLong(jsApiTicketArg[1]);
				long diffTime = Long.parseLong(jsApiTicketArg[2]);
				if (Math.abs(nowTime - putTime) >= diffTime) {
					System.out
							.println("################################################");
					System.out.println("载入JsApiTicket已超时，重新载入");
					System.out
							.println("################################################");
					newJsApiTicket = reloadJsApiTicket((String) map.get("id"), "0").getTicket();
				} else {
					newJsApiTicket = jsApiTicketArg[0];
				}
			}
		}
		return newJsApiTicket;
	}

	/**
	 * 重新装载JsApiTicket
	 *
	 * @return
	 */
	public JsApiTicket reloadJsApiTicket(String id, String type)
	{
		String accessToken = getAccessToken();
		JsApiTicket jsApiTicket = WechatJsApiTicket.getJsApiTicket(accessToken);
		Map<String, String> map = new HashMap<String, String>();
		map.put("JSAPI_TICKET", jsApiTicket.getTicket() + ","
				+ new Date().getTime() + ","
				+ (jsApiTicket.getExpiresIn() * 1000));
		if("1".equals(type)){
			map.put("id", UuidUtil.get32UUID());
		}else{
			map.put("id", id);
		}
		try {
			if("1".equals(type))//添加
			{
				dao.save("WxUtilDao.saveAccessToken",map);
			}else{
				dao.update("WxUtilDao.updateJsApiToken",map);
			}
		} catch (Exception e) {
		}
		return jsApiTicket;
	}


	/**
	 * 验证accessToken是否有效
	 * @param accessToken true:有效 false：无效
	 * @return
	 */
	public boolean select_accessToken(String accessToken)
	{
		try
		{
			String ip_list="";
			//空
			if(Tools.isEmpty(accessToken))
			{
				return false;
			}
			//获取微信服务器IP地址，目前用于验证access_token是否有效
			String select_access_token_url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN";

			String requestUrl = select_access_token_url.replace("ACCESS_TOKEN", accessToken);

			JSONObject jsonObject = HttpRequestUtil.httpRequest(requestUrl,
					EnumMethod.GET.name(), null);
			if (jsonObject == null)
			{
				jsonObject = HttpRequestUtil.httpRequest(requestUrl,
						EnumMethod.GET.name(), null);
			}
			// 如果请求成功
			if (null != jsonObject)
			{
				try
				{
					ip_list=jsonObject.getString("ip_list").toString();

				} catch (JSONException e)
				{
					ip_list = null;
				}
			}

			if(Tools.isEmpty(ip_list))
			{
				return false;
			}
			else
			{
				return true;
			}

		} catch (Exception e)
		{
			return false;
		}

	}



}
